package com.szsky.sky.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.szsky.sky.entity.app.UmcAppDeviceToken;
import com.szsky.sky.entity.app.UmcAppSn;
import com.szsky.sky.service.app.UmcAppDeviceTokenService;
import com.szsky.sky.service.app.UmcAppSnService;
import com.szsky.sky.service.app.UmcAppVersionService;
import com.szsky.sky.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/app")
public class AppController {

    @Value("${map.key}")
    private String mapKey;

    @Resource
    private UmcAppSnService umcAppSnService;
    @Resource
    private UmcAppVersionService umcAppVersionService;
    @Resource
    private UmcAppDeviceTokenService umcAppDeviceTokenService;

    @GetMapping("/getSn")
    public Result getSn(@RequestParam String appKey) {
        UmcAppSn umcAppSn = umcAppSnService.getSn(appKey);
        if (BeanUtil.isNotEmpty(umcAppSn)) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", umcAppSn.getId());
            map.put("appId", umcAppSn.getAppId());
            map.put("sn", umcAppSn.getSn());
            map.put("url", umcAppSn.getUrl());
//            Integer updateCount = umcAppSnService.updateSn(umcAppSn.getSn());
            return Result.success(map);
        } else {
            return Result.success("无兑换码可用！");
        }
    }

    @GetMapping("/getVersion")
    public Result getVersion(@RequestParam String currentVersion, @RequestParam String appType) {
        Map map = umcAppVersionService.getVersion(currentVersion, appType);
        return Result.success(map);
    }

    @GetMapping("/getMapKey")
    public Result getMapKey() {
        return Result.success(mapKey);
    }

    @PostMapping("/saveDeviceToken")
    public Result saveDeviceToken(UmcAppDeviceToken appDeviceToken) {
        UmcAppDeviceToken umcAppDeviceToken = umcAppDeviceTokenService.saveDeviceToken(appDeviceToken);
        return Result.success(umcAppDeviceToken);
    }

    @PostMapping("/queryDeviceToken")
    public Result queryDeviceToken(String str) {
        List<String> receiveAccountList = JSON.parseArray(str, String.class);
        List<String> tokenList = umcAppDeviceTokenService.queryDeviceToken(receiveAccountList);
        if (CollectionUtil.isNotEmpty(tokenList)) {
            return Result.success(tokenList);
        } else {
            return Result.success(null);
        }
    }

}
